﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Model.Enum.MessageEnum;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace BLL.Manage
{
    public class FriendsManage
    {
        /// <summary>
        /// 发送通知 添加好友
        /// </summary>
        public Model.Result<string> AddFriends(string toMemberId, string message)
        {
            var user = new UserManage().UserTokenModel;
            if (toMemberId == user.MemberId)
            {
                return RestfulAPIModel.ErrorReult<string>("傻逼，请不要自己添加自己");
            }
            using (Model.Entity.DBContext context = new Model.Entity.DBContext())
            {
                var findMessage = context.SocialMessage.FirstOrDefault(p => p.FromMemberId == user.MemberId && p.ToMemberId == toMemberId);
                if (findMessage != null && findMessage.IsHandle != 1)
                {
                    return RestfulAPIModel.ErrorReult<string>("操作成功");
                }
                var find = context.User.FirstOrDefault(p => p.MemberId == toMemberId);
                if (find != null)
                {
                    // 添加好友消息 好友存在的时候
                    var findIsFriends = context.Friends.FirstOrDefault(p => p.MemberId == user.MemberId && p.FriendMemberId == toMemberId);
                    if (findIsFriends != null)
                    {
                        // 已经是好友关系
                        return RestfulAPIModel.ErrorReult<string>("已是好友关系");
                    }
                    else
                    {
                        var findIsToFriendMessage = context.SocialMessage
                            .FirstOrDefault(p => p.ToMemberId == toMemberId && p.MessageId == user.MemberId && p.IsRead == (int)MessageIsRead.notRead);
                        if (findIsToFriendMessage != null)
                        {
                            return RestfulAPIModel.SuccessReult<string>();
                        }

                        context.SocialMessage.Add(new Model.Entity.SocialMessage()
                        {
                            CreateTime = DateTime.Now,
                            FromMemberId = user.MemberId,
                            ReadTime = DateTime.Now,
                            ToMemberId = toMemberId,
                            MessageType = (int)SocialMessageType.addFriend,
                            HandleResult = (int)MessageHandleResult.fail,
                            IsHandle = (int)MessageIsHandle.notHandle,
                            // 关联
                            Rocial = (int)MessageRocial.friend,
                            IsRead = (int)MessageIsRead.notRead,
                            MessageId = System.Guid.NewGuid().ToString("N"),
                            SendMessage = message
                        });
                        //context.ChatMessage.Add() ;
                        var model = new Model.Entity.ChatMessage()
                        {
                            Content = "",
                            ContentType = 1,
                            CreateTime = DateTime.Now,
                            IsRead = 0,
                            IsReceiver = 1,
                            MessageId = System.Guid.NewGuid().ToString("N"),
                            MessageType = (int)Model.Enum.MessageEnum.SocialMessageType.addFriend,
                            ReadTime = DateTime.Now,
                            ReceiverId = toMemberId,
                            ReceiverTime = DateTime.Now,
                            ReceiverStatus = 1,
                            SenderId = user.MemberId
                        };
                        var state = BLL.Wapper.WebSocketWapper.SendObjectAsync(toMemberId, new Model.Basics.UserModel.SocketMessageTamplate()
                        {
                            Content = "",
                            ContentType = 1,
                            SocketMessageType = (int)Model.Enum.MessageEnum.SocialMessageType.addFriend,
                            ReceiverID = model.ReceiverId,
                            SenderID = model.SenderId
                        });
                        context.ChatMessage.Add(model);
                        context.SaveChanges();
                        //BLL.Wapper.WebSocketWapper.SendStringAsync()
                        return RestfulAPIModel.SuccessReult<string>("操作成功");
                    }
                }
                else
                {
                    // 好友不存在
                    return RestfulAPIModel.ErrorReult<string>("用户不存在");
                }
            };
        }

        /// <summary>
        /// 处理消息
        /// </summary>
        /// <returns></returns>
        public Model.Result<string> HanldeMessager(string messageId, Model.Enum.MessageEnum.MessageHandleResult messageHansleResult, string handleMessage = null)
        {
            var user = new UserManage().UserTokenModel;
            using (Model.Entity.DBContext dbContext = new Model.Entity.DBContext())
            {
                var findOne = dbContext.SocialMessage.FirstOrDefault(p => p.MessageId == messageId && p.IsHandle == 0);
                if (findOne == null || findOne.IsHandle == 1)
                {
                    return RestfulAPIModel.ErrorReult<string>("消息不存在或已处理");
                }
                else if (findOne.FromMemberId == user.MemberId)
                {
                    return RestfulAPIModel.ErrorReult<string>("逗比，自己添加自己？");
                }
                else
                {

                    findOne.IsHandle = (int)messageHansleResult;
                    findOne.IsRead = (int)MessageIsRead.isRead;
                    findOne.HandleResult = (int)messageHansleResult;
                    findOne.ReadTime = DateTime.Now;
                    findOne.HandleMessage = handleMessage;
                    if (findOne.HandleResult == 1)
                    {
                        switch (findOne.MessageType)
                        {
                            case (int)SocialMessageType.addFriend:
                                this.HandleAddToFriends(findOne.FromMemberId);
                                break;
                        }
                    }
                    dbContext.SaveChanges();
                    // 添加好友
                    return RestfulAPIModel.SuccessReult<string>("操作成功");
                }
            }
        }

        /// <summary>
        /// 获取好友列表
        /// </summary>
        public List<Model.ApiResult.FriendResult.FriendsList> GetFriendList()
        {
            var user = new UserManage().UserTokenModel;
            var table = MySqlDb.GetDataTable(@"SELECT
	                            friends.*, `user`.nick_name,
	                            `user`.avatar
                            FROM
	                            friends
                            LEFT JOIN `user` ON friends.member_id = `user`.member_id
                            WHERE
	                            friends.disabled = 0 and friends.friend_member_id=@member_id;",
            new MySql.Data.MySqlClient.MySqlParameter[] {
                new MySql.Data.MySqlClient.MySqlParameter("member_id",user.MemberId)
            });
            return MySqlDb.ErgodicDataTable(table, (DataRow dr) =>
                {
                    var model = new Model.ApiResult.FriendResult.FriendsList();
                    model.GroupName = null;
                    model.AsGroup = null;
                    model.Avatar = ConvertHelper.ConverToAny<string>(dr["avatar"]);
                    model.FriendMemberId = ConvertHelper.ConverToAny<string>(dr["friend_id"]);
                    model.FriendRemark = ConvertHelper.ConverToAny<string>(dr["friend_remark"]);
                    model.NickName = ConvertHelper.ConverToAny<string>(dr["nick_name"]);
                    model.ChatRoomId = ConvertHelper.ConverToAny<string>(dr["friend_relation_id"]);
                    return model;
                });
        }

        /// <summary>
        /// 处理好友添加
        /// </summary>
        public void HandleAddToFriends(string friendMemberid)
        {
            var user = new UserManage().UserTokenModel;
            using (Model.Entity.DBContext dbContext = new Model.Entity.DBContext())
            {
                var findOneOther = dbContext.SocialMessage
                    .FirstOrDefault(p => p.MessageType == (int)SocialMessageType.addFriend && p.FromMemberId == friendMemberid && p.ToMemberId == user.MemberId);
                if (findOneOther != null)
                {
                    findOneOther.IsHandle = 1;
                    findOneOther.IsRead = (int)MessageIsRead.notRead;
                    findOneOther.HandleResult = 1;
                    findOneOther.ReadTime = DateTime.Now;
                }
                string friendRelationId = System.Guid.NewGuid().ToString("N");
                // 添加两条信息
                var listMolde = new List<Model.Entity.Friends>()
                {
                    new Model.Entity.Friends()
                    {
                        FriendId=System.Guid.NewGuid().ToString("N"),
                        MemberId = user.MemberId,
                        FriendMemberId = friendMemberid,
                        CreateTime = DateTime.Now,
                        FriendRelationId=friendRelationId
                    },
                    new Model.Entity.Friends()
                    {
                        FriendId=System.Guid.NewGuid().ToString("N"),
                        MemberId = friendMemberid,
                        FriendMemberId = user.MemberId,
                        CreateTime = DateTime.Now,
                        FriendRelationId=friendRelationId
                    }
                };
                dbContext.Friends.AddRange(listMolde);
                dbContext.SaveChanges();
            }
        }

        /// <summary>
        /// 通过ID或者用户昵称查询好友
        /// </summary>
        /// <param name="nickNameOrId">ID或者用户昵称</param>
        /// <returns></returns>
        public List<Model.ApiResult.FriendResult.SearchFriendListResult> SearchFriendListResult(string nickNameOrId)
        {
            var user = new UserManage().UserTokenModel;
            var table = MySqlDb.GetDataTable(@"
            SELECT
                `user`.*,
                F1.friend_remark,
                F1.member_id as my_member_id,
                F1.friend_relation_id
            FROM
                `user`
            LEFT JOIN friends F1 ON F1.friend_member_id = `user`.member_id
            AND F1.member_id = @member_id
            WHERE
                `user`.user_id like @search_nameorid
            OR `user`.nick_name like @search_nameorid;",
            new MySql.Data.MySqlClient.MySqlParameter[] {
                new MySql.Data.MySqlClient.MySqlParameter("member_id",user.MemberId),
                new MySql.Data.MySqlClient.MySqlParameter("search_nameorid","%"+ nickNameOrId+"%"),
            });
            return MySqlDb.ErgodicDataTable<Model.ApiResult.FriendResult.SearchFriendListResult>(table, (DataRow dr) =>
             {
                 var model = new Model.ApiResult.FriendResult.SearchFriendListResult();
                 model.NickName = MySqlDb.ChangeTableData<string>(dr["nick_name"]);
                 model.Avatar = MySqlDb.ChangeTableData<string>(dr["avatar"]);
                 model.MemberId = MySqlDb.ChangeTableData<string>(dr["member_id"]);
                 model.RemarkName = MySqlDb.ChangeTableData<string>(dr["friend_remark"]);
                 model.IsFreind = (MySqlDb.ChangeTableData<string>(dr["my_member_id"]) != null);
                 model.IsGouper = false;
                 model.UserId = MySqlDb.ChangeTableData<string>(dr["user_id"]);
                 model.FriendRelationId = MySqlDb.ChangeTableData<string>(dr["friend_relation_id"]);
                 return model;
             });
        }

        /// <summary>
        /// 判断是不是好友
        /// </summary>
        /// <param name="friendId">好友ID</param>
        /// <returns></returns>
        public bool IsFriends(string friendId)
        {
            UserManage user = new UserManage();
            if (user.UserTokenModel == null)
            {
                return false;
            }
            using (Model.Entity.DBContext context = new Model.Entity.DBContext())
            {
                var find = context.Friends.FirstOrDefault(p => p.FriendMemberId == friendId && p.MemberId == user.UserTokenModel.MemberId);
                return find != null;
            }
        }
    }
}
